<template>
  <div class="factory-page">
    <div class="header">
      <h2 class="title">{{ pageTitle }}</h2>
      <div class="status">
        <el-tag :type="hasTask ? (isHistory ? 'success' : (progress === 100 ? 'success' : 'warning')) : 'info'"
          effect="plain" class="status-tag">
          <el-icon v-if="hasTask" :class="isHistory || progress === 100 ? 'success-icon' : 'warning-icon'">
            <Check v-if="isHistory || progress === 100" />
            <Loading v-else />
          </el-icon>
          {{ hasTask ? (isHistory ? '已完成' : (progress === 100 ? '已完成' : '生成中')) : '无任务' }}
        </el-tag>

        <el-tag v-if="hasTask && progress === 100" type="success" effect="plain" class="edit-hint-tag">
          <Edit class="edit-icon" />
          文案支持编辑修改
        </el-tag>

      </div>
    </div>

    <div class="h-progress" v-if="hasTask && !isHistory">
      <div class="h-step" :class="{ done: progress >= 10 }">准备</div>
      <div class="h-step" :class="{ done: progress >= 40 }">内容生成</div>
      <div class="h-step" :class="{ done: progress >= 70 }">排版优化</div>
      <div class="h-step" :class="{ done: progress >= 100 }">发布准备</div>
      <div class="h-bar">
        <div class="h-fill" :style="{ width: progress + '%' }"></div>
      </div>
    </div>

    <!-- <div class="tabs"> -->
    <div v-if="hasTask">

      <div class="publish-status-container">
        <div v-for="(status, platform) in publishStatus.platforms" :key="platform" class="publish-status"
          :class="status.status">
          <div class="status-indicator"></div>
          <div class="status-content">
            <div class="status-platform">{{ getPlatformName(platform) }}</div>
            <div class="status-message">{{ status.message }}</div>
          </div>
          <el-button size="small" circle @click="clearPublishStatus(platform)" class="status-close"
            :icon="CircleClose"></el-button>
        </div>
      </div>

      <el-tabs v-model="active">
        <el-tab-pane label="微博内容" name="weibo" v-if="showPlatforms.weibo">
          <template #label>
            <span>
              <img src="/微博.svg" width="16" height="16" style="vertical-align: middle; margin-right: 4px;">
              微博内容
            </span>
          </template>
          <WeiboEditor :content="formattedWeiboContent" :hashtags="formattedWeiboHashtags"
            @publish="publishToPlatform"
            @content-update="handleWeiboContentUpdate" />
          <!-- <WeiboEditor :content="formattedWeiboContent" :hashtags="formattedWeiboHashtags"
              :suggestions="currentContent.weiboSuggestions" @publish="publishToPlatform" /> -->
        </el-tab-pane>
        <el-tab-pane label="抖音内容" name="douyin" v-if="showPlatforms.douyin">
          <template #label>
            <span>
              <img src="/抖音.svg" width="16" height="16" style="vertical-align: middle; margin-right: 4px;">
              抖音内容
            </span>
          </template>
          <DouyinEditor :content="formattedDouyinContent" :script="currentContent.douyinScript"
            :suggestions="currentContent.douyinSuggestions" @publish="publishToPlatform"
             />
          <!-- <DouyinEditor :content="formattedDouyinContent" :script="currentContent.douyinScript"
            :suggestions="currentContent.douyinSuggestions" @publish="publishToPlatform" /> -->
        </el-tab-pane>
        <el-tab-pane label="微信内容" name="wechat" v-if="showPlatforms.wechat">
          <template #label>
            <span>
              <img src="/微信公众号.svg" width="16" height="16" style="vertical-align: middle; margin-right: 4px;">
              微信公众号内容
            </span>
          </template>
          <WechatEditor :content="formattedWechatContent" :suggestions="currentContent.wechatSuggestions"
            @publish="publishToPlatform"
            />
          <!-- <WechatEditor :content="formattedWechatContent" :suggestions="currentContent.wechatSuggestions"
            @publish="publishToPlatform" /> -->
        </el-tab-pane>
      </el-tabs>
    </div>

    <div v-else class="empty-state">
      <div class="empty-icon">
        <el-icon class="big-icon">
          <Edit />
        </el-icon>
      </div>
      <div class="empty-title">欢迎使用热点内容创作工厂</div>
      <div class="empty-desc">请返回"热点雷达"页面，选择感兴趣的热点并点击"一键生成"开始创作。</div>
      <el-button type="primary" @click="navigateToHotspot">前往热点雷达</el-button>

      <div class="features-tip">
        <el-tag type="success" effect="plain" size="large" class="feature-tag">
          <Edit class="edit-icon" />
          文案支持编辑修改
        </el-tag>
        <el-tag type="success" effect="plain" size="large" class="feature-tag">
          <Message class="info-icon" />
          实时字数统计
        </el-tag>
        <el-tag type="success" effect="plain" size="large" class="feature-tag">
          <CollectionTag class="tag-icon" />
          话题标签一键插入
        </el-tag>
      </div>
    </div>
    <!-- </div> -->

  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, watch, computed, reactive } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { STORAGE_KEYS } from '../utils/constants';
import { getSourceIcon, getStatsIcon } from '../utils/iconMaps';
import { Check, Loading, Close, Edit, CircleClose, Message, CollectionTag } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import WeiboEditor from './Editor/WeiboEditor.vue'
import DouyinEditor from './Editor/DouyinEditor.vue'
import WechatEditor from './Editor/WechatEditor.vue'
// 引入文案格式化函数和话题标签格式化函数
import { formatCopywriting, formatHashtags } from '../utils/formatters'
// 文案格式化函数
// const formatCopywriting = (content, platform) => {
//   if (!content) return ''

//   let formattedContent = content

//   // 基础格式化：处理换行和段落
//   formattedContent = formattedContent
//     .replace(/\n\n+/g, '</p><p>')
//     .replace(/\n/g, '<br>')

//   // 为不同平台添加特定格式
//   switch (platform) {
//     case 'wechat':
//       // 微信公众号格式：标题、段落、强调、排版优化
//       formattedContent = formattedContent
//         // 处理一级标题
//         .replace(/^#\s+(.*?)$/gm, '<h1 class="wechat-main-title">$1</h1>')
//         // 处理二级标题
//         .replace(/^##\s+(.*?)$/gm, '<h2 class="wechat-subtitle">$1</h2>')
//         // 处理【标题】格式
//         .replace(/【(.*?)】/g, '<strong class="wechat-title">$1</strong>')
//         // 处理内容分段
//         .replace(/^(标题：|导语：|正文：|结尾：)/gm, '<div class="wechat-section">$1</div>')
//         // 处理列表
//         .replace(/^(\d+)\.\s+(.*?)$/gm, '<div class="wechat-list-item"><span class="wechat-list-number">$1.</span> $2</div>')
//         // 中英文之间添加空格
//         .replace(/([\u4e00-\u9fa5])([a-zA-Z])/g, '$1 $2')
//         .replace(/([a-zA-Z])([\u4e00-\u9fa5])/g, '$1 $2')
//       break

//     case 'weibo':
//       // 微博格式：话题标签高亮、排版优化
//       formattedContent = formattedContent
//         // 话题标签高亮
//         .replace(/#([^#]+)#/g, '<span class="weibo-hashtag">#$1#</span>')
//         // 强调内容
//         .replace(/【(.*?)】/g, '<strong class="weibo-highlight">$1</strong>')
//         // 中英文之间添加空格
//         .replace(/([\u4e00-\u9fa5])([a-zA-Z])/g, '$1 $2')
//         .replace(/([a-zA-Z])([\u4e00-\u9fa5])/g, '$1 $2')
//       break

//     case 'douyin':
//       // 抖音格式：脚本分段和强调、排版优化
//       formattedContent = formattedContent
//         // 内容分段
//         .replace(/^(视频脚本|背景音乐|画面描述|旁白|字幕)：/gm, '<div class="douyin-section">$1：</div>')
//         // 强调内容
//         .replace(/【(.*?)】/g, '<strong class="douyin-highlight">$1</strong>')
//         // 处理#挑战名称#格式
//         .replace(/#挑战([^#]+)#/g, '<span class="douyin-challenge">#挑战$1#</span>')
//         // 中英文之间添加空格
//         .replace(/([\u4e00-\u9fa5])([a-zA-Z])/g, '$1 $2')
//         .replace(/([a-zA-Z])([\u4e00-\u9fa5])/g, '$1 $2')
//       break
//   }

//   // 确保有段落包裹
//   if (!formattedContent.startsWith('<p>') && !formattedContent.startsWith('<div') && !formattedContent.startsWith('<h1') && !formattedContent.startsWith('<h2')) {
//     formattedContent = `<p>${formattedContent}</p>`
//   }

//   return formattedContent
// }

// 格式化话题标签
// const formatHashtags = (hashtags) => {
//   if (!hashtags || !Array.isArray(hashtags)) return []
//   return hashtags.map(tag => {
//     if (typeof tag === 'string') {
//       return tag.startsWith('#') ? tag : `#${tag}`
//     }
//     return tag
//   })
// }

// 计算属性：格式化后的内容
const formattedWeiboContent = computed(() => formatCopywriting(currentContent.value.weibo, 'weibo'))
const formattedDouyinContent = computed(() => formatCopywriting(currentContent.value.douyin, 'douyin'))
const formattedWechatContent = computed(() => formatCopywriting(currentContent.value.wechat, 'wechat'))
const formattedWeiboHashtags = computed(() => formatHashtags(currentContent.value.weiboHashtags))

// Element Plus已在组件中全局引入

const route = useRoute()
const router = useRouter()
const active = ref('weibo')
const pageTitle = ref('热点内容创作')
const progress = ref(0)
const messages = ref([])
const hasTask = ref(false)
const isHistory = ref(false) // 标记是否为历史记录
const currentContent = ref({
  weibo: '',
  weiboHashtags: [],
  weiboSuggestions: [],
  douyin: '',
  douyinScript: '',
  douyinSuggestions: [],
  wechat: '',
  wechatSuggestions: []
})

// 在creationFactory.vue的脚本中
const handleWeiboContentUpdate = (newContent) => {
  // 更新父组件中的内容（根据实际数据结构调整）
  currentContent.value.weibo = newContent;
};
// 发布状态管理 - 修改为支持多平台状态跟踪
const publishStatus = reactive({
  platforms: {} // 以平台ID为键，存储每个平台的发布状态
})

// 发布到指定平台
// const publishToPlatform = async (publishData) => {
//   const { platform, content } = publishData

//   // 更新特定平台的发布状态，而不是覆盖整个状态对象
//   publishStatus.platforms[platform] = {
//     status: 'pending',
//     message: `正在发布到${getPlatformName(platform)}...`,
//     timestamp: new Date()
//   }

//   // 显示加载状态，并保存消息引用
//   const loadingMessage = ElMessage({
//     message: `正在发布到${getPlatformName(platform)}...`,
//     type: 'info',
//     duration: 0
//   })

//   // 设置超时检测，避免用户长时间等待
//   let timeoutTimer = setTimeout(() => {
//     this.$message({
//       message: '发布请求处理中，请稍候...',
//       type: 'info',
//       duration: 2000
//     })
//   }, 5000) // 5秒后提示用户请求正在处理中

//   try {
//     // 获取平台和风格设置
//     let savedPlatforms = null
//     let savedStyles = '["专业严谨"]'
//     try {
//       savedPlatforms = localStorage.getItem('selectedPlatforms')
//       savedStyles = localStorage.getItem('selectedStyles') || '["专业严谨"]'
//     } catch (error) {
//       console.warn('无法访问localStorage，使用默认值:', error)
//     }

//     const platforms = savedPlatforms ? JSON.parse(savedPlatforms) : { wechat: true, weibo: true, douyin: true }
//     const styles = JSON.parse(savedStyles)

//     // 准备发布数据
//     const publishParams = {
//       hotspot_title: pageTitle.value.replace(/\s*hotspot内容创作$/, ''),
//       hotspot_content: '',
//       platforms: platforms,
//       styles: styles,
//       platforms_to_publish: [platform],
//       publish_schedule: 'immediate'
//     }

//     // 调用发布API，增加请求超时控制
//     const controller = new AbortController()
//     const timeoutId = setTimeout(() => controller.abort(), 10000) // 10秒超时

//     // 为apiService.publishContent添加信号参数，或者直接调用底层请求方法
//     // 这里我们使用apiService.post直接调用，以便控制超时
//     const result = await apiService.post('/publish/execute', publishParams)
//     clearTimeout(timeoutId)

//     // 清除超时提示定时器
//     clearTimeout(timeoutTimer)

//     // 关闭加载消息
//     loadingMessage.close()

//     if (result && result.success) {
//       // 更新特定平台的发布状态
//       publishStatus.platforms[platform] = {
//         status: 'success',
//         message: `${getPlatformName(platform)}发布成功！`,
//         timestamp: new Date()
//       }

//       // 立即显示成功消息，不再等待后续处理
//       ElMessage({
//         message: `${getPlatformName(platform)}发布成功！`,
//         type: 'success',
//         duration: 3000
//       })
//       return result
//     } else {
//       const errorMessage = result && result.message ? result.message : `${getPlatformName(platform)}发布失败`
//       // 更新特定平台的发布状态
//       publishStatus.platforms[platform] = {
//         status: 'error',
//         message: errorMessage,
//         timestamp: new Date()
//       }
//       throw new Error(errorMessage)
//     }
//   } catch (error) {
//     // 清除所有定时器
//     clearTimeout(timeoutTimer)
//     clearTimeout(timeoutId)

//     // 关闭加载消息
//     loadingMessage.close()

//     console.error('发布失败:', error)

//     // 处理超时错误
//     let errorMessage
//     if (error.name === 'AbortError') {
//       errorMessage = '发布请求超时，请检查网络连接并重试'
//     } else {
//       errorMessage = error.message || '发布失败，请稍后重试'
//     }

//     // 更新特定平台的发布状态
//     publishStatus.platforms[platform] = {
//       status: 'error',
//       message: errorMessage,
//       timestamp: new Date()
//     }

//     ElMessage({
//       message: errorMessage,
//       type: 'error',
//       duration: 5000
//     })
//     return null // 不再抛出异常，避免影响组件状态更新
//   }
// }
// const publishToPlatform = async (publishData) => {
//   const { platform, content, hashtags } = publishData


//   // 2. 准备发布参数（根据接口要求组装）
//   const publishParams = {
//     platform: platform,
//     content: content,  // 子组件传递的HTML内容
//     hashtags: hashtags,  // 子组件提取的话题标签
//     // 其他必要参数（如标题、发布时间等）
//     hotspot_title: pageTitle.value,
//     publish_schedule: 'immediate'
//   }

//   // 3. 调用发布API
//   try {
//     const result = await apiService.post('/publish/execute', publishParams)
//     if (result.success) {
//       ElMessage({
//         message: '微博发布成功！',
//         type: 'success'
//       })
//     }
//   } catch (error) {
//     ElMessage({
//       message: '发布失败：' + error.message,
//       type: 'error'
//     })
//   }
// }
const publishToPlatform = async (publishData) => {
  console.log('🎯 接收到发布数据:', publishData)
  
  const { platform, content, hashtags } = publishData

  // 清理和验证数据
  const cleanContent = (content || '').trim().replace(/[\x00-\x1F\x7F]/g, '') // 移除控制字符
  const cleanTitle = pageTitle.value.replace(/\s*hotspot内容创作$/, '').trim()
  
  // 详细日志
  console.log('📤 清理后的发布请求:', {
    platform: platform,
    content: cleanContent,
    contentLength: cleanContent.length,
    hashtags: hashtags || ['话题1'],
    hashtagsCount: (hashtags || []).length,
    hotspot_title: cleanTitle
  })

  // 准备发布参数
  const publishParams = {
    platform: platform,
    content: cleanContent,
    hashtags: hashtags || [],
    hotspot_title: cleanTitle,
    publish_schedule: 'immediate'
  }

  console.log('📦 完整请求参数:', JSON.stringify(publishParams, null, 2))

  // 调用发布API
  try {
    const result = await apiService.post('/publish/execute', publishParams)
    console.log('✅ API响应:', result)
    
    if (result && result.success) {
      ElMessage({
        message: `${getPlatformName(platform)}发布成功！`,
        type: 'success'
      })
    } else {
      const errorMsg = result?.message || '发布失败，未知错误'
      ElMessage({
        message: errorMsg,
        type: 'error'
      })
    }
  } catch (error) {
    console.error('❌ API调用失败:', error)
    // ElMessage({
    //   message: '发布失败：' + (error.message || '网络错误'),
    //   type: 'error'
    // })
  }
}

// 获取平台中文名
const getPlatformName = (platform) => {
  const platformMap = {
    weibo: '微博',
    douyin: '抖音',
    wechat: '微信公众号'
  }
  return platformMap[platform] || platform
}

// 清除发布状态
const clearPublishStatus = (platform = null) => {
  if (platform) {
    // 清除特定平台的发布状态
    delete publishStatus.platforms[platform]
  } else {
    // 清除所有平台的发布状态
    publishStatus.platforms = {}
  }
}
// 控制平台显示
const showPlatforms = ref({
  weibo: true,
  douyin: true,
  wechat: true
})

// 导入API服务
import apiService from '../services/apiService'


// 新增：获取第一个有内容的平台
const getFirstAvailablePlatform = (content, platformsConfig) => {
  // 检查平台的优先级顺序：微博 -> 抖音 -> 微信公众号
  const platformOrder = ['weibo', 'douyin', 'wechat']

  for (const platform of platformOrder) {
    // 检查平台是否启用且有内容
    if (platformsConfig[platform]) {
      switch (platform) {
        case 'weibo':
          if (content.weibo) return platform
          break
        case 'douyin':
          if (content.douyin) return platform
          break
        case 'wechat':
          if (content.wechat) return platform
          break
      }
    }
  }

  // 如果没有有内容的平台，返回第一个启用的平台
  return platformOrder.find(platform => platformsConfig[platform]) || 'weibo'
}

// 生成文案函数
const generateCopywriting = async (title, content) => {
  try {
    // 获取选中的平台和风格
    let savedPlatforms = null
    let savedStyles = '["专业严谨"]'
    try {
      savedPlatforms = localStorage.getItem('selectedPlatforms')
      savedStyles = localStorage.getItem('selectedStyles') || '["专业严谨"]'
    } catch (error) {
      console.warn('无法访问localStorage，使用默认值:', error)
    }

    const platforms = savedPlatforms ? JSON.parse(savedPlatforms) : { wechat: true, weibo: true, douyin: true }
    const styles = JSON.parse(savedStyles)

    // 使用统一的API服务
    const result = await apiService.generateCopywriting({
      hotspot_title: title,
      hotspot_content: content,
      platforms: platforms,
      styles: styles
    })

    if (result.success && result.data) {
      // 内容生成成功后自动切换到第一个有内容的平台
      const firstPlatform = getFirstAvailablePlatform(result.data, platforms);
      active.value = firstPlatform;
      return result.data;
    } else {
      throw new Error(result.message || '文案生成失败')
    }
  } catch (error) {
    console.error('生成文案失败:', error)
    throw error
  }
}

// Element Plus已在组件中全局引入

// 微信编辑器组件
// const WechatEditor = {
//   props: ['content', 'suggestions'],
//   emits: ['publish'],
//   template: `<div class="card">
//     <div class="editor-title">微信公众号内容 <span class="editor-hint">(支持编辑)</span></div>
//     <div class="editor-box wechat-content" 
//          contenteditable="true"
//          @input="handleContentChange"
//          v-html="editableContent || '无内容'"></div>
//     <div v-if="suggestions && suggestions.length" class="suggestions">
//       <div class="suggestion-title">发布建议：</div>
//       <ul>
//         <li v-for="(suggestion, index) in suggestions" :key="index">{{ suggestion }}</li>
//       </ul>
//     </div>
//     <div class='actions'>
//       <el-button @click="resetContent">取消</el-button>
//       <el-button type='primary' @click="copyContent">复制文案</el-button>
//       <el-button type='primary' @click="handlePublish" :loading="publishing">发布</el-button>
//     </div>
//   </div>`,
//   data() {
//     return {
//       publishing: false,
//       editableContent: ''
//     }
//   },
//   watch: {
//     content: {
//       handler(newVal) {
//         this.editableContent = newVal
//       },
//       immediate: true
//     }
//   },
//   methods: {
//     handleContentChange(event) {
//       this.editableContent = event.target.innerHTML
//       console.log(this.editableContent)
//     },
//     resetContent() {
//       this.editableContent = this.content
//     },
//     copyContent() {
//       // 从contenteditable中获取纯文本内容
//       const tempDiv = document.createElement('div')
//       tempDiv.innerHTML = this.editableContent
//       const text = tempDiv.textContent || tempDiv.innerText || ''

//       if (navigator.clipboard && navigator.clipboard.writeText) {
//         navigator.clipboard.writeText(text).then(() => {
//           ElMessage({
//             message: '文案已复制到剪贴板',
//             type: 'success',
//             duration: 2000
//           })
//         }).catch(() => {
//           ElMessage({
//             message: '复制失败，请手动复制',
//             type: 'error',
//             duration: 2000
//           })
//         })
//       } else {
//         ElMessage({
//           message: '浏览器不支持复制功能，请手动复制',
//           type: 'warning',
//           duration: 2000
//         })
//       }
//     },
//     async handlePublish() {
//       this.publishing = true
//       try {
//         await this.$emit('publish', { platform: 'wechat', content: this.editableContent })
//       } finally {
//         this.publishing = false
//       }
//     }
//   }
// }

// 微博编辑器组件
// const WeiboEditor = {
//   props: ['content', 'hashtags', 'suggestions'],
//   emits: ['publish'],
//   template: `<div class="card">
//     <div class="editor-title">微博内容 <span class="editor-hint">(支持编辑)</span></div>
//     <div class="editor-box weibo-content" 
//          contenteditable="true"
//          @input="handleContentChange"
//          v-html="editableContent || '无内容'"></div>
//     <div class="char-count" :class="{ warning: charCount > 130, error: charCount > 140 }">
//       {{ charCount }}/140
//     </div>
//     <div v-if="hashtags && hashtags.length" class="hashtags">
//       <div class="hashtag-title">话题标签：</div>
//       <div class="hashtag-list">
//         <span v-for="(tag, index) in hashtags" :key="index" class="hashtag" @click="insertTag(tag)">{{ tag }}</span>
//       </div>
//     </div>
//     <div v-if="suggestions && suggestions.length" class="suggestions">
//       <div class="suggestion-title">发布建议：</div>
//       <ul>
//         <li v-for="(suggestion, index) in suggestions" :key="index">{{ suggestion }}</li>
//       </ul>
//     </div>
//     <div class='actions'>
//       <el-button @click="resetContent">取消</el-button>
//       <el-button type='primary' @click="copyContent">复制文案</el-button>
//       <el-button type='primary' @click="handlePublish" :loading="publishing" :disabled="charCount > 140">发布</el-button>
//     </div>
//   </div>`,
//   data() {
//     return {
//       publishing: false,
//       editableContent: ''
//     }
//   },
//   computed: {
//     charCount() {
//       const tempDiv = document.createElement('div')
//       tempDiv.innerHTML = this.editableContent
//       return (tempDiv.textContent || tempDiv.innerText || '').length
//     }
//   },
//   watch: {
//     content: {
//       handler(newVal) {
//         this.editableContent = newVal
//       },
//       immediate: true
//     }
//   },
//   methods: {
//     handleContentChange(event) {
//       this.editableContent = event.target.innerHTML
//       console.log(this.editableContent)
//     },
//     resetContent() {
//       this.editableContent = this.content
//     },
//     copyContent() {
//       const tempDiv = document.createElement('div')
//       tempDiv.innerHTML = this.editableContent
//       const text = tempDiv.textContent || tempDiv.innerText || ''

//       if (navigator.clipboard && navigator.clipboard.writeText) {
//         navigator.clipboard.writeText(text).then(() => {
//           ElMessage({
//             message: '文案已复制到剪贴板',
//             type: 'success',
//             duration: 2000
//           })
//         }).catch(() => {
//           ElMessage({
//             message: '复制失败，请手动复制',
//             type: 'error',
//             duration: 2000
//           })
//         })
//       } else {
//         ElMessage({
//           message: '浏览器不支持复制功能，请手动复制',
//           type: 'warning',
//           duration: 2000
//         })
//       }
//     },
//     insertTag(tag) {
//       // 插入标签到光标位置
//       const selection = window.getSelection()
//       if (selection.rangeCount > 0) {
//         const range = selection.getRangeAt(0)
//         const textNode = document.createTextNode(tag + ' ')
//         range.insertNode(textNode)
//         range.setStartAfter(textNode)
//         range.setEndAfter(textNode)
//         selection.removeAllRanges()
//         selection.addRange(range)
//       }
//       // 更新内容
//       const editorDiv = document.querySelector('.weibo-content[contenteditable="true"]')
//       if (editorDiv) {
//         this.editableContent = editorDiv.innerHTML
//       }
//     },
//     async handlePublish() {
//       this.publishing = true
//       try {
//         await this.$emit('publish', { platform: 'weibo', content: this.editableContent, hashtags: this.hashtags })
//       } finally {
//         this.publishing = false
//       }
//     }
//   }
// }



// 抖音编辑器组件
// const DouyinEditor = {
//   props: ['content', 'script', 'suggestions'],
//   emits: ['publish'],
//   template: `<div class='card'>
//     <div class='editor-title'>抖音内容 <span class="editor-hint">(支持编辑)</span></div>
//     <div class='editor-box douyin-content' 
//          contenteditable="true"
//          @input="handleContentChange"
//          v-html="editableContent || '无内容'"></div>
//     <div v-if="script" class="script">
//       <div class="script-title">视频脚本：</div>
//       <div class="script-content" 
//            contenteditable="true"
//            @input="handleScriptChange"
//            v-text="editableScript"></div>
//     </div>
//     <div v-if="suggestions && suggestions.length" class="suggestions">
//       <div class="suggestion-title">发布建议：</div>
//       <ul>
//         <li v-for="(suggestion, index) in suggestions" :key="index">{{ suggestion }}</li>
//       </ul>
//     </div>
//     <div class='actions'>
//       <el-button @click="resetContent">取消</el-button>
//       <el-button type='primary' @click="copyContent">复制文案</el-button>
//       <el-button type='primary' @click="handlePublish" :loading="publishing">发布</el-button>
//     </div>
//   </div>`,
//   data() {
//     return {
//       publishing: false,
//       editableContent: '',
//       editableScript: ''
//     }
//   },
//   watch: {
//     content: {
//       handler(newVal) {
//         this.editableContent = newVal
//       },
//       immediate: true
//     },
//     script: {
//       handler(newVal) {
//         this.editableScript = newVal
//       },
//       immediate: true
//     }
//   },
//   methods: {
//     handleContentChange(event) {
//       this.editableContent = event.target.innerHTML
//       console.log(this.editableContent)
//     },
//     handleScriptChange(event) {
//       this.editableScript = event.target.textContent || event.target.innerText
//       console.log(this.editableScript)
//     },
//     resetContent() {
//       this.editableContent = this.content
//       this.editableScript = this.script
//     },
//     copyContent() {
//       const tempDiv = document.createElement('div')
//       tempDiv.innerHTML = this.editableContent
//       const text = (tempDiv.textContent || tempDiv.innerText || '') + '\n\n视频脚本：\n' + this.editableScript

//       if (navigator.clipboard && navigator.clipboard.writeText) {
//         navigator.clipboard.writeText(text).then(() => {
//           ElMessage({
//             message: '文案已复制到剪贴板',
//             type: 'success',
//             duration: 2000
//           })
//         }).catch(() => {
//           ElMessage({
//             message: '复制失败，请手动复制',
//             type: 'error',
//             duration: 2000
//           })
//         })
//       } else {
//         ElMessage({
//           message: '浏览器不支持复制功能，请手动复制',
//           type: 'warning',
//           duration: 2000
//         })
//       }
//     },
//     async handlePublish() {
//       this.publishing = true
//       try {
//         await this.$emit('publish', {
//           platform: 'douyin',
//           content: this.editableContent,
//           script: this.editableScript
//         })
//       } finally {
//         this.publishing = false
//       }
//     }
//   }
// }

watch(
  () => route.query,
  async (newQuery) => {
    // 从路由参数获取标题
    const title = newQuery.title ? decodeURIComponent(newQuery.title) : ''
    const id = newQuery.id
    if (title) {
      pageTitle.value = `${title} `
      hasTask.value = true
      let savedPlatforms = null
      try {
        savedPlatforms = localStorage.getItem('selectedPlatforms')
      } catch (error) {
        console.warn('无法访问localStorage，使用默认平台:', error)
      }

      if (savedPlatforms) {
        showPlatforms.value = JSON.parse(savedPlatforms)
      }
      // 判断是否为历史记录
      if (id) {
        isHistory.value = true
        progress.value = 100
        // 从 localStorage 读取历史内容
        let history = []
        try {
          history = JSON.parse(localStorage.getItem(STORAGE_KEYS.HISTORY_RECORD) || '[]')
        } catch (error) {
          console.warn('无法访问localStorage，使用空历史记录:', error)
        }
        const target = history.find(item => item.id === id)
        currentContent.value = target?.content || { weibo: '', douyin: '', wechat: '' }
        if (target?.platforms) {
          showPlatforms.value = target.platforms
        }
        messages.value = ['已加载历史记录内容', '内容格式已还原', '可直接编辑发布']
        // 加载历史记录时自动切换到第一个有内容的平台
        const firstPlatform = getFirstAvailablePlatform(currentContent.value, showPlatforms.value)
        active.value = firstPlatform
      } else {
        // 真实生成过程
        try {
          progress.value = 10

          // 从路由参数获取热点内容，避免重复API调用
          const hotspotContent = newQuery.content ? decodeURIComponent(newQuery.content) : '暂无详细内容'

          progress.value = 30

          // 调用文案生成API
          const copywritingResult = await generateCopywriting(title, hotspotContent)

          progress.value = 70

          // 更新内容
          if (copywritingResult.weibo) {
            currentContent.value.weibo = copywritingResult.weibo.content || copywritingResult.weibo
            currentContent.value.weiboHashtags = copywritingResult.weibo.hashtags || []
          }
          if (copywritingResult.douyin) {
            currentContent.value.douyin = copywritingResult.douyin.content || copywritingResult.douyin
            currentContent.value.douyinScript = copywritingResult.douyin.video_script || ''
          }
          if (copywritingResult.wechat) {
            currentContent.value.wechat = copywritingResult.wechat.content || copywritingResult.wechat
            currentContent.value.wechatSuggestions = copywritingResult.wechat.suggestions || []
          }

          progress.value = 100

          // 保存到历史记录
          try {
            const title = pageTitle.value.replace(/\s*hotspot内容创作$/, '')
            let history = []
            try {
              history = JSON.parse(localStorage.getItem(STORAGE_KEYS.HISTORY_RECORD) || '[]')
            } catch (error) {
              console.warn('无法访问localStorage，无法保存历史记录:', error)
            }
            const now = new Date().toLocaleString()
            const newId = Date.now().toString()

            const contentToSave = {}
            if (showPlatforms.value.weibo) contentToSave.weibo = currentContent.value.weibo
            if (showPlatforms.value.douyin) contentToSave.douyin = currentContent.value.douyin
            if (showPlatforms.value.wechat) contentToSave.wechat = currentContent.value.wechat

            const newRecord = {
              id: newId,
              title,
              time: now,
              content: contentToSave,
              platforms: showPlatforms.value
            }

            const list = [newRecord, ...history].slice(0, 50)
            try {
              localStorage.setItem(STORAGE_KEYS.HISTORY_RECORD, JSON.stringify(list))
              const event = new CustomEvent('history-updated', { detail: list })
              window.dispatchEvent(event)
            } catch (error) {
              console.warn('无法保存到localStorage:', error)
            }
          } catch (e) {
            console.error('保存历史记录失败', e)
          }
        } catch (error) {
          console.error('文案生成失败:', error)
          // 生成失败时使用示例内容
          currentContent.value.weibo = '文案生成失败，请稍后重试。错误信息：' + error.message
          currentContent.value.douyin = '文案生成失败，请稍后重试。错误信息：' + error.message
          currentContent.value.wechat = '文案生成失败，请稍后重试。错误信息：' + error.message
          progress.value = 100
        }
      }
    } else {
      hasTask.value = false
    }
  },
  { immediate: true }
)

// 组件挂载时的默认内容处理
onMounted(() => {
  // 如果没有任务（即没有路由参数），提供演示内容
  if (!hasTask.value) {
    // 显示一个友好的提示，说明如何使用创作工厂
    ElMessage({
      message: '欢迎使用热点内容创作工厂！请从热点雷达页面选择热点并点击「一键生成」开始创作。',
      type: 'info',
      duration: 5000
    })
  }
})

// 重置组件状态的函数
const resetComponentState = () => {
  hasTask.value = false
  isHistory.value = false
  progress.value = 0
  messages.value = []
  // 清空当前内容
  currentContent.value = {
    weibo: '',
    weiboHashtags: [],
    weiboSuggestions: [],
    douyin: '',
    douyinScript: '',
    douyinSuggestions: [],
    wechat: '',
    wechatSuggestions: []
  }
  // 清空发布状态
  Object.keys(publishStatus.platforms).forEach(platform => {
    delete publishStatus.platforms[platform]
  })
}

// 导航到热点雷达页面的函数
const navigateToHotspot = () => {
  // 在导航前立即重置状态
  resetComponentState()

  // 使用微任务确保DOM更新后再执行导航
  setTimeout(() => {
    router.push('/hotspot')
  }, 0)
}

// 组件卸载时重置状态，确保跳转页面时清理数据
onBeforeUnmount(() => {
  resetComponentState()
})
</script>


<style scoped>
.publish-status-container {
  display: flex;
  flex-direction: column;
  gap: 8px;
  margin-bottom: 16px;
}

.publish-status {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  border-radius: 8px;
  background-color: #f5f7fa;
  border: 1px solid #ebeef5;
}

.publish-status.pending {
  background-color: #ecf5ff;
  border-color: #b3d8ff;
}

.publish-status.success {
  background-color: #f0f9eb;
  border-color: #b7eb8f;
}

.publish-status.error {
  background-color: #fef0f0;
  border-color: #ffccc7;
}

.status-indicator {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  margin-right: 12px;
  background-color: #909399;
}

.publish-status.pending .status-indicator {
  background-color: #409eff;
}

.publish-status.success .status-indicator {
  background-color: #67c23a;
}

.publish-status.error .status-indicator {
  background-color: #f56c6c;
}

.status-content {
  flex: 1;
}

.status-platform {
  font-weight: 600;
  font-size: 14px;
  margin-bottom: 4px;
}

.status-message {
  font-size: 14px;
  color: #606266;
}

.status-close {
  margin-left: 12px;
}

.factory-page {
  display: block;
  padding: 24px;
}

.status-tag {
  padding: 6px 12px;
  font-size: 14px;
  font-weight: 500;
}

.success-icon {
  color: #10b981;
  margin-right: 6px;
}

.warning-icon {
  color: #f59e0b;
  margin-right: 6px;
  animation: spin 1.5s linear infinite;
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }

  to {
    transform: rotate(360deg);
  }
}

.header {
  grid-column: 1 / -1;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.tabs {
  width: 98%;
  background: #fff;
  border: 1px solid #eee;
  border-radius: 8px;
  padding: 0 12px;
  margin-top: 20px;
}

.empty-state {
  padding: 60px 12px;
  text-align: center;
  color: #6b7280;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 20px;
  color: #409eff;
}

.big-icon {
  font-size: 64px;
}

.empty-title {
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 12px;
  color: #303133;
}

.empty-desc {
  font-size: 14px;
  margin-bottom: 24px;
  line-height: 1.6;
  color: #606266;
}

.empty-title {
  font-weight: 600;
  color: #111827;
  margin-bottom: 8px;
}

.empty-desc {
  font-size: 13px;
}


.edit-hint-tag {
  margin-left: 8px;
  font-size: 14px;
}

.editor-hint {
  font-size: 12px;
  color: #67c23a;
  font-weight: normal;
}


.editor-box[contenteditable="true"] {
  min-height: 100px;
  padding: 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  outline: none;
  transition: border-color 0.3s;
  background-color: #fff;
}

.editor-box[contenteditable="true"]:focus {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1);
}


.char-count {
  text-align: right;
  font-size: 12px;
  color: #909399;
  margin-top: 8px;
}

.char-count.warning {
  color: #e6a23c;
}

.char-count.error {
  color: #f56c6c;
}


.hashtag {
  cursor: pointer;
  transition: all 0.3s;
}

.hashtag:hover {
  color: #409eff;
  background-color: #ecf5ff;
}

.script-content[contenteditable="true"] {
  min-height: 80px;
  padding: 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  outline: none;
  transition: border-color 0.3s;
  background-color: #fff;
  white-space: pre-wrap;
  word-break: break-word;
}

.script-content[contenteditable="true"]:focus {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1);
}

.features-tip {
  margin-top: 20px;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  justify-content: center;
}


.edit-icon,
.info-icon,
.tag-icon {
  margin-right: 4px;
  width: 20px;
  height: 20px;
  vertical-align: middle;
}

.feature-tag {
  font-size: 16px;
  font-weight: bold;
  display: inline-flex;
  align-items: center;
}

.h-progress {
  grid-column: 1 / -1;
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 8px;
  align-items: center;
  margin: 12px 0 8px;
}

.h-step {
  font-size: 12px;
  color: #9ca3af;
  text-align: center;
}

.h-step.done {
  color: #2563eb;
  font-weight: 600;
}

.h-bar {
  grid-column: 1 / -1;
  height: 8px;
  background: #eef2f7;
  border-radius: 9999px;
  overflow: hidden;
}

.h-fill {
  height: 100%;
  background: linear-gradient(90deg, #93c5fd, #3b82f6);
  width: 0;
  transition: width .6s ease;
}

.card {
  padding: 16px;
}

.editor-title {
  font-weight: 600;
  margin-bottom: 8px;
}

.editor-box {
  background: #f9fafb;
  border: 1px solid #eef2f7;
  border-radius: 8px;
  padding: 12px;
  min-height: 120px;
  white-space: pre-wrap;
}

.suggestions,
.hashtags,
.script {
  margin-top: 12px;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 6px;
}

.suggestion-title,
.hashtag-title,
.script-title {
  font-weight: 600;
  margin-bottom: 8px;
  color: #4b5563;
}

.hashtag-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.hashtag {
  background: #3b82f6;
  color: white;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.script-content {
  white-space: pre-wrap;
  font-size: 14px;
  line-height: 1.5;
}

.actions {
  margin-top: 12px;
  display: flex;
  gap: 8px;
}

.wechat-content {
  line-height: 1.8;
  font-size: 16px;
  color: #333;
  font-family: 'Microsoft YaHei', 'PingFang SC', serif;
}

.wechat-content .wechat-main-title {
  font-size: 22px;
  font-weight: bold;
  color: #1a1a1a;
  margin: 24px 0 16px 0;
  text-align: center;
}


.wechat-content .wechat-subtitle {
  font-size: 18px;
  font-weight: 600;
  color: #2a2a2a;
  margin: 20px 0 12px 0;
  text-align: center;
}


.wechat-content .wechat-title {
  font-size: 18px;
  font-weight: bold;
  color: #1a1a1a;
  display: block;
  margin: 16px 0 8px 0;
}


.wechat-content .wechat-section {
  font-weight: 600;
  color: #2c5aa0;
  margin: 16px 0 12px 0;
  padding-left: 8px;
  border-left: 3px solid #2c5aa0;
}


.wechat-content p {
  margin: 12px 0;
  text-align: justify;
  text-indent: 2em;
}


.wechat-content .wechat-list-item {
  margin: 8px 0;
  padding-left: 24px;
}

.wechat-content .wechat-list-number {
  font-weight: 600;
  color: #2c5aa0;
}


.wechat-content strong {
  font-weight: bold;
  color: #1a1a1a;
}

.wechat-content em {
  font-style: italic;
  color: #666;
}

.weibo-content {
  line-height: 1.5;
  font-size: 15px;
  color: #333;
  font-family: 'Microsoft YaHei', 'PingFang SC', sans-serif;
}

.weibo-content .weibo-hashtag {
  color: #ff6b35;
  font-weight: 600;
  text-decoration: none;
  padding: 2px 4px;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.weibo-content .weibo-hashtag:hover {
  background-color: #fff5f0;
}

.weibo-content .weibo-highlight {
  color: #ff6b35;
  font-weight: 600;
}


.weibo-content p {
  margin: 12px 0;
  text-align: left;
}


.weibo-content img[alt*="表情"] {
  vertical-align: middle;
  margin: 0 2px;
}


.douyin-content {
  line-height: 1.2;
  font-size: 16px;
  color: #333;
  font-family: 'Heiti SC', 'Microsoft YaHei', sans-serif;
}


.douyin-content .douyin-section {
  font-weight: 600;
  color: #ff2d55;
  margin: 12px 0 8px 0;
  padding: 6px 10px;
  background: #fff5f7;
  border-radius: 4px;
  font-size: 17px;
}


.douyin-content .douyin-highlight {
  color: #ff2d55;
  font-weight: 600;
  font-size: 17px;
}


.douyin-content .douyin-challenge {
  color: #ff2d55;
  font-weight: bold;
  background: #fff0f3;
  padding: 2px 6px;
  border-radius: 4px;
  margin: 0 2px;
}


.douyin-content p {
  margin: 10px 0;
  text-align: left;
  font-size: 16px;
}

.script-content {
  line-height: 1.5;
  font-size: 15px;
  color: #333;
  font-family: 'Heiti SC', 'Microsoft YaHei', sans-serif;
}

.script-content[contenteditable="true"] {
  line-height: 1.6;
  font-size: 15px;
}
</style>